const Mock = require('mockjs')
const bodyParser = require('body-parser');
const { list } = Mock.mock({
    'list|40': [
        {
            img: '@image(500x500,@color)',
            name: "@name(2)",
            id: '@id',
        }]
})

module.exports = (app) => {
    app.use(bodyParser.json())
    app.get('/api/lists', (req, res) => { 
        res.send({
            code: 200,
            msg: "全部数据",
            list
        })
    })

    app.get('/api/sort/lists', (req, res) => { //排序
        let newList = JSON.parse(JSON.stringify(list))
        if (req.query.val === 'name') {
            newList.sort((x, y) => { return x.name.localeCompare(y.name) })
        } else if (req.query.val === 'price') {
            newList.sort((x, y) => { return x.price - y.price })
        }
        res.send({
            code: 200,
            msg: '排序',
            newList
        })
    })

    app.get('/api/buy/lists', (req, res) => { //未购买
        res.send({
            code: 200,
            msg: '未购买',
            newList: list.filter(v => !v.buy)
        })
    })

    app.post('/api/buy/lists', (req, res) => { //购买商品
        list.map(v => {
            if (v.id === req.body.id) {
                v.buy = true
            }
            return;
        })
        res.send({
            code: 200,
            msg: '购买成功',
            list
        })
    })
}